import BaseView from "../../../Script/Base/BaseView";
import { EBundleType, EResType, EViewType } from "../../../Script/Common/Enum";
import EventID from "../../../Script/Common/EventID";
import { TalkModule } from "../../../Script/Common/TalkModule";
import { IFlyResData, IMessage, IStoreData, IStoreItem, IStoreUpItem, ITalkData, IViewData } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import AppService from "../../../Script/Service/AppService";
import GameUtil from "../../../Script/Util/GameUtil";
import StorageUtil from "../../../Script/Util/StorageUtil";
import Counter from "./Counter";
import Hall from "./Hall";
import StockGame from "./StockGame";
import TownUI from "../town/TownUI";
import { LoadUtil } from "../../Util/LoadUtil";
import GameUI from "../GameUI";

const { ccclass, property } = cc._decorator;

const VIEW_DATA: IViewData = {
    name: 'StoreUI',
    type: EViewType.Panel,
    bundle: EBundleType.Game,
    zIndex: 100,
};

// 小卖店玩法
@ccclass
export default class StoreUI extends BaseView implements IMessage {
    public static instance: StoreUI = null;

    @property({ type: [cc.Node], tooltip: "大厅/货柜/进货" })
    private views: cc.Node[] = [];

    @property({ type: cc.Node, tooltip: "货柜气泡节点" })
    private bubble: cc.Node = null;

    @property({ type: cc.Label, tooltip: "货柜获得金额" })
    private labMoney: cc.Label = null;

    @property({ type: cc.Label, tooltip: "上货按钮数量" })
    private labCounterInfo: cc.Label = null;

    private viewId: number = 0;
    
    private talkData: ITalkData = null;
    private storeData: IStoreData = null;

    recvMsg(cmd: number, data: any) {
        switch (cmd) {
            case EventID.TEST_CMD:
                {

                }
                break;
        }
    }

    protected onLoad() {
        super.onLoad();
        this.addMessage(EventID.TEST_CMD, this);

        StoreUI.instance = this;

        this.talkData = StorageUtil.instance.getTalkData();
        this.storeData = StorageUtil.instance.getStoreData();

        this.refreshUI();
        this.refreshMoney();
        this.updateCounterInfo();
        this.check();
    }

    private isfirst: boolean = true;

    public async check() {
        if (!this.talkData) {
            return;
        }

        this.updateLine();
        this.showFightUI();
    }

    /** 展示FightUI */
    private showFightUI() {
        if (this.talkData.id === 11104) {
            if (this.isfirst) {
                this.isfirst = false;
                // 通过弹窗的方式添加会展示UI层，所以单独处理
                LoadUtil.instance.loadRes(EBundleType.Game, 'prefab/panel/FightUI', cc.Prefab, (err, res) => {
                    const node = cc.instantiate(res) as cc.Node;
                    node.parent = SceneGame.instance.getToastNode();
                    console.log("pk花大妈:", this.talkData.id);
                });
            }
        }
    }

    private updateLine() {
        switch (this.talkData.id) {
            case 11008:
                this.talkData.id = 11101;
                TalkModule.updateCheck();
                break;
        }
    }

    public refreshUI() {
        this.views.forEach((o, i) => {
            o.active = i === this.viewId;
            if (this.talkData.id > 114) {
                if (o.active) {
                    switch (i) {
                        case 0:
                            o.getComponent(Hall).refreshUI();
                            break;
                        case 1:
                            o.getComponent(Counter).refreshUI();
                            break;
                        case 2:
                            o.getComponent(StockGame).restart();
                            break;
                    }
                }
            }
        });
    }

    /** 设置数据 */
    public setRewards(temp: IStoreItem[]) {
        let add = (reward: IStoreItem) => {
            const data = this.getStoreDataById(reward.id);
            if (!data) {
                this.storeData.downItems.push(reward);
            } else {
                data.num += reward.num;
            }
        }

        for (let i = 0; i < temp.length; i++) {
            add && add(temp[i]);
        }
        add = null;
    }

    /** 刷新剩余库存 */
    public refreshData(id: number, num: number) {
        const reward = this.getStoreDataById(id);
        reward.num += num;
    }

    /** 根据id获取库存数据 */
    public getStoreDataById(id: number) {
        const reward = this.storeData.downItems.find((o) => o.id === id);
        return reward;
    }

    /** 更新货架数量显示 */
    public updateCounterInfo() {
        let total = 0;
        let datas = this.storeData.upItems;
        datas.forEach((o) => {
            if (o.item.id > -1)  {
                total += o.item.num;
            }
        });
        this.labCounterInfo.string = `${total}/${3 * 6 * 5}`;
    }

    public getCounterItems() {
        const node = this.views[1].getComponent(Counter).getCounterItems();
        return node;
    }

    public refreshMoney(add: number = 0) {
        this.storeData.stockMoney += add;
        this.labMoney.string = `${this.storeData.stockMoney}`;
    }

    public openOtherNode(id: number) {
        this.isHasChild = true;
        this.viewId = id;
        this.refreshUI();
    }

    public onCloseChild() {
        this.isHasChild = false;
        this.viewId = 0;
        this.refreshUI();
    }

    public onCloseClicked() {
        super.onCloseClicked();
        TownUI.instance.check();
        GameUI.instance.check();
    }

    private onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case 'btnCounter':
            case 'btnCounterInfo':
                {
                    this.openOtherNode(1);
                }
                break;
            case 'btnStock':
                {
                    this.openOtherNode(2);
                }
                break;
            case 'btnBubble':
                {
                    if (this.storeData.stockMoney <= 0) {
                        return;
                    }

                    const data = SceneGame.instance.getFlyResData();
                    const flyData: IFlyResData = {
                        resType: EResType.Money,
                        parent: data.flyNode,
                        from: this.bubble,
                        to: data.money,
                        value: this.storeData.stockMoney,
                        flyTimes: 10,
                        maxWidth: 60,
                        maxHeight: 60
                    }
                    GameUtil.instance.flyResIcon(flyData);

                    // 清空金额
                    this.refreshMoney(-this.storeData.stockMoney);
                }
                break;
        }
    }
}
AppService.instance.registViewData(VIEW_DATA);